# FIGURE 1
# Authors: Mark Kayser & Kasia Nalewajko
# First created: Feb 28, 2024
# Replicated: Nov 18, 2025

rm(list = ls())

# LOAD PACKAGES -----------------------------------------------------------

if (!require("dplyr")) install.packages("dplyr")
if (!require("glmnet")) install.packages("glmnet")
if (!require("marginaleffects")) install.packages("marginaleffects")
if (!require("ggplot2")) install.packages("ggplot2")

# LOAD DATA ---------------------------------------------------------------

setwd("set/path/to/folder")

load(file = "./01 data/02 generated data/study1/01results_fullsample_clean.Rda")


# RUN MODELS AND PLOT ----

# LEFT PANE: PO supporters who want to rerun the election

# Run the logit model

# recode outcome
results <- results %>% 
  filter(outcome != 99) %>%
  mutate(outcome_supports = ifelse(outcome > 5, 1, 0))

temp <- results %>% 
  filter(manipulation_check1 == 3 | (is.na(manipulation_check1))) %>%  
  filter(popis == "PO",
         !is.na(GSparty_id_z))

modelPO <- glm(outcome_supports ~ exp_condition*GSparty_id_z + experiment_first + as.factor(voivodeship), data = temp, family = binomial(link=logit))

# Plot

plot_predictions(modelPO,
                 type = "response",
                 condition = c("GSparty_id_z", "exp_condition")) +
  labs(title = "PO supporters, PiS wins",
       x = "Standardised strength of partisanship",
       y = "Predicted probability of wanting to rerun the election") +
  theme_minimal() +
  scale_color_manual(values = c("PiSwins" = "blue", "POwins" = "transparent", "control" = "transparent")) +
  scale_fill_manual(values = c("PiSwins" = "blue", "POwins" = "transparent", "control" = "transparent")) +
  theme(legend.position = "none") +
  ylim(-0.05, 1.05)

# RIGHT PANE: PiS supporters who want to rerun the election ----

temp <- results %>% 
  filter(manipulation_check1 == 3 | (is.na(manipulation_check1))) %>%  
  filter(popis == "PiS",
         !is.na(GSparty_id_z))

modelPiS <- glm(outcome_supports ~ exp_condition*GSparty_id_z + experiment_first + as.factor(voivodeship), data = temp, family = binomial(link=logit))
summary(modelPiS)

plot_predictions(modelPiS,
                 type = "response",
                 condition = c("GSparty_id_z", "exp_condition")) +
  labs(title = "PiS supporters, PO wins",
       x = "Standardised strength of partisanship",
       y = "Predicted probability of wanting to rerun the election") +
  theme_minimal() +
  scale_color_manual(values = c("POwins" = "red", "PiSwins" = "transparent", "control" = "transparent")) +
  scale_fill_manual(values = c("POwins" = "red", "PiSwins" = "transparent", "control" = "transparent")) +
  theme(legend.position = "none") +
  ylim(-0.05, 1.05)


